﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Linq;
using Abp.AspNetCore.Mvc.Controllers;
using Abp.Dependency;
using Abp.Events.Bus;
using Abp.Json;
using Castle.Core.Logging;
using Magicodes.WeChat.SDK;
using Magicodes.WeChat.SDK.Apis.TemplateMessage;
using Magicodes.WeChat.SDK.Core.ServerMessages;
using Magicodes.WeChat.SDK.Core.ServerMessages.From;
using Magicodes.WeChat.SDK.Core.ServerMessages.To;
using Magicodes.WeChat.SDK.Pays.TenPayV3;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace Magicodes.WeChat.Web.Core
{
    [AllowAnonymous]
    [Route("WeChatPayNotify")]
    public class WeChatPayNotifyController : AbpController
    {
        public IIocResolver IocResolver { get; set; }

        /// <summary>
        /// 根据key存储的支付函数
        /// </summary>
        public static Dictionary<string, Action<NotifyResult, IIocResolver, bool>> PayActions =
            new Dictionary<string, Action<NotifyResult, IIocResolver, bool>>();

        /// <summary>
        /// 默认支付函数
        /// </summary>
        public static Action<string, NotifyResult, IIocResolver, bool> DefaultPayAction { get; set; }

        [HttpPost("{tenantId}")]
        public ActionResult PayNotify(int? tenantId)
        {
            Logger.Debug("正在处理微信支付信息");
            void SuccessAction(NotifyResult result)
            {
                var resultLog = result.ToJsonString();
                Logger.Info("微信支付处理成功: " + resultLog);
                //获取微信支付自定义数据
                string key;
                if (string.IsNullOrWhiteSpace(result.Attach))
                {
                    Logger.Error("自定义数据为空！");
                    return;
                }
                //获取Key
                if (result.Attach.StartsWith("{"))
                {
                    var data = JsonConvert.DeserializeObject<JObject>(result.Attach);
                    key = data["key"].ToString();
                }
                else
                {
                    key = result.Attach;
                }
                if (PayActions.ContainsKey(key))
                {
                    Logger.Info("微信支付处理成功，正在回调key: " + key);
                    PayActions[key].Invoke(result, IocResolver, true);
                }
                else
                {
                    if (DefaultPayAction == null)
                        Logger.Error("微信支付处理成功，没有找到回调key: " + key);

                    DefaultPayAction?.Invoke(key, result, IocResolver, true);
                }
            }

            void FailAction(NotifyResult result)
            {
                //此处编写失败处理逻辑
                var failLog = result.ToJsonString();
                Logger.Error("微信支付处理失败: " + failLog);
                var key = result.Attach;
                if (PayActions.ContainsKey(key))
                {
                    Logger.Info("微信支付处理失败，正在回调key: " + key);
                    PayActions[key].Invoke(result, IocResolver, false);
                }
                else
                {
                    Logger.Error("微信支付处理失败，没有找到回调key: " + key);
                }
            }

            var payApi = new TenPayV3();
            //TODO:统一微信端租户Id的获取
            payApi.SetKey(tenantId ?? 1);
            var contentResult = payApi.NotifyAndReurnResult(Request.Body, SuccessAction,
                FailAction);
            Logger.Debug("支付处理：" + contentResult);
            return Content(contentResult);
        }
    }
}
